<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三极分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品牌分类，级联选择框所在的行 -->
      <el-row class="cat_opt">
        <el-col>
          <!-- 级联选择器选择商品分类 -->
          <span>选择商品分类：</span>
          <el-cascader
            :options="cateList"
            v-model="selectedKeys"
            :props="{
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
              children: 'children'
            }"
            @change="handleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tabs -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            @click="addParams()"
            size="mini"
            :disabled="isBtnDisalbed"
          >
            添加参数
          </el-button>
          <el-table :data="manyParamsDate" border stripe>
            <el-table-column width="40" type="expand">
              <template v-slot:default="scope">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, scope.row)"
                  >{{ tag }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="40">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="editParams(scope.row)"
                  icon="el-icon-edit"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            @click="addParams()"
            size="mini"
            :disabled="isBtnDisalbed"
          >
            添加属性
          </el-button>
          <el-table :data="onlyParamsDate" border stripe>
            <el-table-column width="40" type="expand">
              <template v-slot:default="scope">
                <el-tag
                  :key="i"
                  v-for="(tag, i) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, scope.row)"
                  >{{ tag }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index" width="40">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="editParams(scope.row)"
                  icon="el-icon-edit"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性按钮的对话框(共用一个对话框) -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addParamsDialogClose()"
    >
      <el-form
        :model="addParamsForm"
        ref="addParamsFormRef"
        status-icon
        :rules="addParamsFormRules"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsBtnOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsDialogClose()"
    >
      <el-form
        :model="editParamsForm"
        ref="editParamsFormRef"
        status-icon
        :rules="editParamsFormRules"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsDialogOk()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      // 级联选择器选中元素的数组
      selectedKeys: [],
      // Tabs当前选中的标签页，默认训中第一项(many表示请求的是动态参数，only是静态属性)
      activeName: 'many',
      // 分类的参数信息,many:动态参数，only静态属性
      manyParamsDate: [],
      onlyParamsDate: [],
      // 添加参数/属性的对话框是否显示
      addDialogVisible: false,
      // 添加参数、属性对话框的from表单
      addParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      // 添加参数、属性对话框的from表单
      editParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      addParamsFormRules: {
        attr_name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      editParamsFormRules: {
        attr_name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      // 修改参数/属性对话框
      editParamsDialogVisible: false,
      // 属性id
      paramsId: 0
    }
  },
  created () {
    this.getCateList()
  },
  // 计算属性
  computed: {
    isBtnDisalbed () {
      // 如果按钮需要被禁用，则返回true，否则返回false
      return this.selectedKeys.length !== 3
    },
    // 当前选中的三级分类的Id
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      // 未选中三级分类
      return null
    },
    titleText () {
      // 对话框的名称
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }

  },
  methods: {
    // 获取三级分类的所有数据，存到cateList中
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      } else {
        this.cateList = res.data
      }
    },
    // 级联选择器改变
    async handleChange (value) {
      if (this.selectedKeys.length !== 3) {
        // 级联选择器选中的不是三级
        this.selectedKeys = []
        this.$message.error('只允许选中三级分类')
        // 重置表格
        this.manyParamsDate = []
        this.onlyParamsDate = []
        return
      }
      // 发送请求
      this.getParamsDate()
    },
    // 获取分类的参数信息，级联选择器改变调用，tabs页面改变调用
    async getParamsDate () {
      // 发送请求：获取分类对应的参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status === 200) {
        // 将attr_vals有字符串转换为数组,为了后面渲染参数下面的tag标签用
        res.data.forEach(item => {
          // 参数没有这个attr_vals就不分割了，空的字符串分割会生成一个数组(一项---空格)
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          // 给其增加新属性，控制文本框的显示与隐藏
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
        })
        // 分类对应的对台参数获取成功res.data
        this.paramsDate = res.data
        if (this.activeName === 'many') {
          this.manyParamsDate = res.data
        }
        if (this.activeName === 'only') {
          this.onlyParamsDate = res.data
        }
      }
      // 将res.data[]中的
    },
    // Tabs切换选项
    handleClick (tab, event) {
      if (this.selectedKeys.length !== 3) {
        // 级联选择器选中的不是三级
        this.selectedKeys = []
      } else {
        this.getParamsDate()
      }
    },
    // 点击添加参数/属性按钮，弹出添加参数对话框
    addParams () {
      this.addDialogVisible = true
    },
    // 添加参数按钮的确认按钮的点击事件
    addParamsBtnOk () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.getParamsDate()
            this.addDialogVisible = false
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    addParamsDialogClose () {
      this.$refs.addParamsFormRef.resetFields()
      // 重置数据，别忘了加
      this.addParamsForm.attr_name = ''
      this.addParamsForm.attr_sel = ''
    },
    // 修改参数按钮
    editParams (row) {
      this.editParamsForm.attr_name = row.attr_name
      // 属性id
      this.paramsId = row.attr_id
      this.editParamsDialogVisible = true
    },
    // 修改参数确认按钮的点击事件
    editParamsDialogOk () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.paramsId}`,
            { attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName })
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.getParamsDate()
            this.editParamsDialogVisible = false
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      })
    },
    editParamsDialogClose () {
      this.$refs.editParamsFormRef.resetFields()
      // 清空数据，别忘了加
      this.editParamsForm.attr_name = ''
      this.editParamsForm.attr_sel = ''
    },
    deleteParams (row) {
      this.paramsId = row.attr_id
      this.$MessageBox.confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(async () => {
        // 发送请求，进行删除用户操作
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${this.paramsId}`)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          this.getParamsDate()
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 点击删除tag
    async handleClose (tag, row) {
      row.attr_vals.splice(row.attr_vals.indexOf(tag), 1)
      // 现在这里的row.attr——vals是数组
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(',') })
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    // 添加新的tag
    async handleInputConfirm (row) {
      // 使用回车键的方式这个函数会被调用两次，@keyup.enter.native会触发，@blur也会触发
      if (row.inputValue.trim().length === 0) {
        // 由于按回车触发的，会执行两次，所以下面这句要注释掉(多一次请求没什么大事,多一个错误消息可就不好了)
        // this.$message.error('输入不合法')
        row.inputValue = ''
        // return
      } else {
        if (row.inputValue) {
          row.attr_vals.push(row.inputValue.trim())
          // 发起请求保存注册操作
          const { data: res } = await this.$http.put(
            `categories/${this.cateId}/attributes/${row.attr_id}`,
            { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(',') })
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.editParamsDialogVisible = false
          } else {
            this.$message.error(res.meta.msg)
          }
        }
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点，$nextTick：当页面上元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 10px 0;
}
.el-tag {
  margin: 5px 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
